<template>
  <div style="padding:20px">
    <el-form label-width="80px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title"/>
      </el-form-item>
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId">
          <el-option v-for="t in teachers" :key="t.id" :label="t.name" :value="t.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="课程类别">
        <el-select v-model="courseInfo.subjectParentId" @change="handleLevelOneSbujectChanged">
          <el-option v-for="p in levelOneSubject" :key="p.id" :label="p.title" :value="p.id"/>
        </el-select>
        <el-select v-model="courseInfo.subjectId">
          <el-option v-for="c in levelTwoSubject" :key="c.id" :label="c.title" :value="c.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="课程课时">
        <el-input-number v-model="courseInfo.lessonNum" :min="1" controls-position="right"/>
      </el-form-item>
      <el-form-item label="课程简介">
        <tinymce v-model="courseInfo.description"/>
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="uploadpath"
          class="avatar-uploader">
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number v-model="courseInfo.price" :min="0" controls-position="right"/>&nbsp;元
      </el-form-item>
    </el-form>
    <div style="margin-top:50px;text-align:center">
      <el-button :disabled="disabled" type="primary" @click="saveAndNext">保存并下一步</el-button>
    </div>
  </div>
</template>
<script>
import teacherApi from '@/api/teacher'
import subjectApi from '@/api/subject'
import Tinymce from '@/components/Tinymce'
import courseApi from '@/api/course'
export default {
  components: { Tinymce },
  data() {
    return {
      uploadpath: 'http://localhost:8120/admin/oss/upload?module=cover',
      levelOneSubject: [],
      levelTwoSubject: [],
      teachers: [],
      courseInfo: {
        lessonNum: 1,
        subjectId: ''// 给subjectId设置默认的数据类型为字符串类型
      }, // 搜集课程基本信息
      disabled: false
    }
  },
  created() {
    // 查询讲师列表数据
    teacherApi.list().then(r => {
      this.teachers = r.data.items
    })
    // 查询一级和子级分类集合
    subjectApi.nestedSubjects().then(r => {
      this.levelOneSubject = r.data.items
      // 获取路径中的id设置给父组件的courseId
      if (this.$route.params.id) {
        this.$parent.courseId = this.$route.params.id
      }
      // 判断如果父组件中courseId的值不为空代表是更新操作 需要回显数据
      if (this.$parent.courseId) {
        courseApi.getById(this.$parent.courseId).then(r => {
          this.courseInfo = r.data.item
          // 课程基本信息中包含了课程一级 分类id，可以根据它查找二级分类集合遍历展示
          this.levelOneSubject.forEach(p => {
            if (p.id === this.courseInfo.subjectParentId) {
              this.levelTwoSubject = p.children
              return
            }
          })
        })
      }
    })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.path
      // 强制渲染
      this.$forceUpdate()
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 一级课程分类选中值变化时回调
    handleLevelOneSbujectChanged(id) {
      // 每次重选一级分类都要清空一下二级的缓存
      this.courseInfo.subjectId = ''
      // 选中的一级分类改变为id的那个
      // 根据id在一级分类中查找一级分类对象，再获取它的子集合设置给二级分类集合
      this.levelOneSubject.forEach(p => {
        if (p.id === id) {
          this.levelTwoSubject = p.children
          return
        }
      })
    },
    saveAndNext() {
      this.disabled = true
      // 判断是新增还是更新
      if (this.$parent.courseId) {
        // 更新
        this.update()
      } else {
        // 新增
        this.save()
      }
    },
    update() {
      courseApi.update(this.courseInfo, this.$parent.courseId).then(r => {
        this.$message.success('更新成功')
        this.$parent.active = 1
      })
    },
    save() {
      courseApi.saveCourseInfo(this.courseInfo).then(r => {
        this.$parent.courseId = r.data.id
        this.$message.success('新增成功')
        console.log(this.$parent.courseId)
        /*
        父子页面的数据交互： 如果一个vue页面以子组件的形式引入一个页面，那么它就是引入页面的父组件
          1、父使用子的属性或方法：
            this.$refs.ref属性值 可以获取父页面中使用的子组件vue对象
            this.$refs.ref属性值.子组件的属性/函数()
          2、子使用父的属性或方法：
            this.$parent  可以获取父vue对象
      */
        // 被点击时 提交课程基本信息到后端 保存成功后再修改 publish.vue页面中 active的值为1
        this.$parent.active = 1
      })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 356px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 356px;
    height: 178px;
    display: block;
  }
  .tinymce-container {
  position: relative;
  line-height: normal;
}
</style>
